package forword;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

@WebServlet("/ywapi")
public class ForwordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String locationUrl = "http://localhost:9080/ywapi";

		String queryValue = request.getQueryString();

		if (StringUtils.isNotBlank(queryValue)) {
			locationUrl += solveUrl(request) + "?" + queryValue;
		}
		IOUtils.write(HttpUtils.sendGet(locationUrl, request), response.getOutputStream());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

	private String solveUrl(HttpServletRequest request) {
		String uri = request.getRequestURI().replaceAll(request.getContextPath(), "");
		// String uri = "/action/sayHello";
		if (uri.indexOf(".") != -1) {
			uri = uri.substring(0, uri.indexOf("."));
		}
		return uri;
	}

	public static void main(String[] args) {
	}

}
